import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def mysave(params,instance):
    if params:
        instance.params = params
        instance.save()


def jwt_response_payload_handler(token,user=None,request=None):
    return {
        'token':token,
        "username":user.username,
        "user_id":user.id,
        'avatar_url':user.avatar_url,
        'nick_name':user.nick_name,
    }

def get_user_by_mobile(mobile):
    try:
        if re.match(r'^1[3-9]\d{9}$',mobile):
            user=User.objects.get(mobile=mobile)
            return user
        else:
            return None
    except User.DoesNotExist:
        return None


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user=get_user_by_mobile(username)
        if user and user.check_password(password):
            return user